package com.leo.blog.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.leo.blog.dto.BlackIpExecution;
import com.leo.blog.entity.BlackIp;
import com.leo.blog.enums.BlackIpStateEnum;
import com.leo.blog.service.BlackIpService;
import com.leo.blog.util.UserIpUtil;

/**
 * 判断是否拉黑
 * @author leo
 *
 */
@Component
public class IpFilter implements Filter{
	
	private ApplicationContext applicationContext = null;
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		//获取到用户的IP
		String ip = UserIpUtil.getIp(request);
		HttpSession session = request.getSession();
		ServletContext servletContext = session.getServletContext();
		BlackIp blackIp = null;
		BlackIpService blackIpServiceImpl = null;
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		blackIpServiceImpl = (BlackIpService) applicationContext.getBean("blackIpServiceImpl");
		BlackIpExecution be = blackIpServiceImpl.getBlackIpByIp(ip);
		if(be.getState() == BlackIpStateEnum.SUCCESS.getState()) {
			request.getRequestDispatcher("../frontend/errorip").forward(request, response);
			//response.sendRedirect("../frontend/errorip");
		}else {
			arg2.doFilter(request, response);
			return;
		}
	}
	
}
